<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElTable } from 'element-plus'
import editorJnmlDialog from '../dialogs/editor-jnml-dialog.vue'
import wsjgDialog from '../dialogs/wsjg-dialog.vue'
import xtpzService from '@/api/xtpz'

const props = defineProps<{
  currrentMbpz: any
}>()

const emit = defineEmits(['changeMb'])

const loading = ref<boolean>(false)

const currentJnIndex = ref<number | null>(null)
const jnlmList = ref<any[]>([])

const filterText = ref('')
/**
 * 获取卷内目录
 */
const getJnmlData = () => {
  const params = {
    gjz: filterText.value,
    mbpzbm: props.currrentMbpz.mbpzbm || '',
  }
  loading.value = true
  xtpzService
    .queryJnml(params)
    .then((res) => {
      if (res) {
        currentJnIndex.value = null
        jnlmList.value = res.data.map((item) => {
          return {
            ...item,
          }
        })
        // if (multipleSelectionJn.value[0]) {
        //   const jnmlbm = multipleSelectionJn.value[0].jnmlbm
        //   nextTick(() => {
        //     const row = jnlmList.value.find((el) => el.jnmlbm === jnmlbm)
        //     multipleJnTableRef.value?.toggleRowSelection(row, true)
        //   })
        // }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

getJnmlData()

const multipleJnTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelectionJn = ref<any[]>([])
const handleSelectionJnChange = (val: any[]) => {
  multipleSelectionJn.value = val
  currentJnIndex.value = jnlmList.value.indexOf(val[0])
}

// 文书接挂点击每一行
const wsjgHandleRowClick = (row: any) => {
  if (multipleSelectionJn.value?.includes(row)) {
    multipleJnTableRef.value?.toggleRowSelection(row, false)
  } else {
    multipleJnTableRef.value?.toggleRowSelection(row, true)
  }
}

/**
 * 添加卷内目录
 */
const editorJnmlDialogRef = ref<InstanceType<typeof editorJnmlDialog>>()
const addJnml = () => {
  editorJnmlDialogRef.value?.openDialog(null, 'add')
}

/**
 * 修改卷内目录
 */
const editorJnml = (row: any, e: Event) => {
  e.stopPropagation()
  editorJnmlDialogRef.value?.openDialog(row, 'update')
}

/**
 * 删除卷内目录
 */
const deleteJnml = () => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let jnmlbm: any = []
    multipleSelectionJn.value.map((el) => {
      jnmlbm.push({
        jnmlbm: el.jnmlbm,
      })
    })
    const params = jnmlbm
    loading.value = true
    xtpzService
      .batchDeleteJnml(params)
      .then(() => {
        ElMessage.success('删除成功')
        getJnmlData()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/**
 * 上移卷内目录
 */
const upJnml = () => {
  if (currentJnIndex.value) {
    const mbIndex = currentJnIndex.value--
    jnlmList.value = swapArrayElements(jnlmList.value, mbIndex, currentJnIndex.value)
    const params = jnlmList.value.map((item, index) => {
      return {
        ...item,
        xh: index + 1,
      }
    })
    loading.value = true
    xtpzService
      .batchUpdateJnmlsx(params)
      .then(() => {
        // getJnmlData()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  }
}

/**
 * 下移卷内目录
 */
const downJnml = () => {
  if (currentJnIndex.value || currentJnIndex.value === 0) {
    const mbIndex = currentJnIndex.value++
    jnlmList.value = swapArrayElements(jnlmList.value, mbIndex, currentJnIndex.value)
    const params = jnlmList.value.map((item, index) => {
      return {
        ...item,
        xh: index - 1,
      }
    })
    loading.value = true
    xtpzService
      .batchUpdateJnmlsx(params)
      .then(() => {
        // getJnmlData()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  }
}

/**
 * 交换顺序
 */
const swapArrayElements = (arr: any[], index1: number, index2: number) => {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0]
  return arr
}

/**
 * 返回
 */
const goBack = () => {
  emit('changeMb', true)
}

/**
 * 文书挂接
 */
const wsjgDialogRef = ref<InstanceType<typeof wsjgDialog>>()
const wsgj = (row: any, e: Event) => {
  e.stopPropagation()
  wsjgDialogRef.value!.openDialog(row)
}
</script>

<template>
  <div class="jnbl-box">
    <div class="btn-box">
      <!-- <div class="table-title">
          <span>归档模板配置</span>
        </div> -->
      <el-input
        class="small-input"
        v-model="filterText"
        placeholder="题名关键字"
        @change="getJnmlData"
        maxlength="100"
      >
        <template #append>
          <el-button class="search-btn" type="primary" @click="getJnmlData">查询</el-button>
        </template>
      </el-input>
      <button class="btn_operation" @click="addJnml">
        <div class="btn-addxzaj"></div>
        添加
      </button>
      <button class="btn_operation" @click="deleteJnml" :disabled="!multipleSelectionJn.length">
        <div class="btn-deletescaj"></div>
        删除
      </button>
      <button
        class="btn_operation"
        :disabled="!currentJnIndex || multipleSelectionJn.length !== 1"
        @click="upJnml"
      >
        <div class="btn-deletescaj"></div>
        上移
      </button>
      <button
        class="btn_operation"
        :disabled="
          currentJnIndex === null ||
          currentJnIndex === jnlmList.length - 1 ||
          multipleSelectionJn.length !== 1
        "
        @click="downJnml"
      >
        <div class="btn-deletescaj"></div>
        下移
      </button>
      <button class="btn_operation" @click="getJnmlData">
        <div class="btn-refresh"></div>
        刷新
      </button>
      <button class="btn_operation" @click="goBack">
        <div class="btn-back"></div>
        返回
      </button>
    </div>
    <el-table
      border
      v-loading="loading"
      ref="multipleJnTableRef"
      :data="jnlmList"
      highlight-current-row
      @row-click="wsjgHandleRowClick"
      @selection-change="handleSelectionJnChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column resizable prop="jnmlmc" label="题名" />
      <el-table-column resizable prop="bz" label="备注" />
      <el-table-column label="操作" width="130">
        <template #default="scope">
          <el-link type="primary" @click="editorJnml(scope.row, $event)">修改</el-link>
          <el-link link type="primary" @click="wsgj(scope.row, $event)">文书挂接</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--添加/修改卷内目录弹框-->
  <editor-jnml-dialog
    ref="editorJnmlDialogRef"
    :mbpzbm="currrentMbpz?.mbpzbm"
    @refresh="getJnmlData"
  />
  <!-- 文书挂接 -->
  <wsjg-dialog
    ref="wsjgDialogRef"
    :currrentMbpz="currrentMbpz"
    :isShowFooter="true"
    @refresh="getJnmlData"
  />
</template>

<style lang="scss" scoped>
.btn-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
  .small-input {
    width: 300px;
    margin-right: 10px;
  }
}
.el-table {
  .el-table--border::after {
    width: 0;
  }
  :deep(.el-table__cell) {
    border-right: 0 !important;
  }
  :deep(.el-table__border-left-patch) {
    display: none;
  }
  :deep(th:not(.el-table-column--selection):not(:last-child)) {
    .cell {
      border-right: 1px solid #d4d1e1;
    }
  }
}
</style>
